package com.msb.mall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class MallCorsConfiguration {
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        // 配置跨域的信息
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        // SpringBoot升级到2.4.0 之后需要使用该配置
        configuration.addAllowedOriginPattern("*");
        configuration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**",configuration);
        return new CorsWebFilter(source);
     /*   UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();

        // 允许的请求头
        configuration.addAllowedHeader("*");

        // 允许的请求方法
        configuration.addAllowedMethod("*");

        // 允许的域名（不能使用 *，需要明确指定）
        configuration.addAllowedOrigin("http://localhost"); // 替换为你的前端域名
        // 如果需要允许多个域名，可以多次调用 addAllowedOrigin
        // configuration.addAllowedOrigin("http://another-domain.com");

        // 允许携带凭证（如 cookies）
        configuration.setAllowCredentials(true);

        // 注册跨域配置，对所有路径生效
        source.registerCorsConfiguration("/**", configuration);

        return new CorsWebFilter(source);*/
    }

}
